# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

"""
操作符映射配置

提供Python操作符到C++操作符的映射。
"""

from typing import Dict

# Python操作符到C++操作符的映射
OPERATOR_MAPPINGS: Dict[str, str] = {
    # 比较操作符
    "==": "==",
    "!=": "!=",
    "<": "<",
    "<=": "<=",
    ">": ">",
    ">=": ">=",
    "is": "==",
    "is not": "!=",
    # 成员检测操作符（需要特殊处理，不能直接映射）
    # "in" 和 "not in" 会通过 __contains__ 方法重载处理
    # 逻辑操作符
    "and": "&&",
    "or": "||",
    "not": "!",
    # 算术操作符
    "+": "+",
    "-": "-",
    "*": "*",
    "/": "/",
    "//": "/",  # 整数除法在C++中也是/
    "%": "%",
    "**": "pow",  # 幂运算需要特殊处理
    # 位操作符
    "&": "&",
    "|": "|",
    "^": "^",
    "~": "~",
    "<<": "<<",
    ">>": ">>",
    # 赋值操作符
    "+=": "+=",
    "-=": "-=",
    "*=": "*=",
    "/=": "/=",
    "%=": "%=",
    "&=": "&=",
    "|=": "|=",
    "^=": "^=",
    "<<=": "<<=",
    ">>=": ">>=",
}

# 操作符优先级映射（用于表达式生成时的括号处理）
OPERATOR_PRECEDENCE: Dict[str, int] = {
    "call": 2,
    "attr": 2,
    "subscript": 2,  # 下标访问
    "unary": 3,
    "**": 4,
    "*": 5,
    "/": 5,
    "//": 5,
    "%": 5,
    "+": 6,
    "-": 6,
    "<<": 7,
    ">>": 7,
    "&": 8,
    "^": 9,
    "|": 10,
    "<": 11,
    "<=": 11,
    ">": 11,
    ">=": 11,
    "==": 11,
    "!=": 11,
    "is": 11,
    "is not": 11,
    "compare": 11,  # 比较操作符的通用优先级
    "not": 12,
    "and": 14,
    "or": 15,
}


def get_operator_mapping(python_op: str) -> str:
    """获取Python操作符对应的C++操作符

    Args:
        python_op: Python操作符

    Returns:
        str: 对应的C++操作符
    """
    return OPERATOR_MAPPINGS.get(python_op, python_op)


def get_operator_precedence(op: str) -> int:
    """获取操作符优先级

    Args:
        op: 操作符

    Returns:
        int: 优先级，数值越小优先级越高
    """
    return OPERATOR_PRECEDENCE.get(op, 100)


def is_special_operator(python_op: str) -> bool:
    """检查是否为需要特殊处理的操作符

    Args:
        python_op: Python操作符

    Returns:
        bool: 是否需要特殊处理
    """
    special_ops = {"**", "//", "is", "is not"}
    return python_op in special_ops
